package cn.lili.controller.member;

import cn.hutool.core.text.CharSequenceUtil;
import cn.lili.cache.Cache;
import cn.lili.cache.CachePrefix;
import cn.lili.common.aop.annotation.DemoSite;
import cn.lili.common.enums.ClientTypeEnum;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Extension;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.dto.ManagerMemberEditDTO;
import cn.lili.modules.member.entity.dto.MemberAddDTO;
import cn.lili.modules.member.entity.enums.PartnerStatusEnum;
import cn.lili.modules.member.entity.vo.*;
import cn.lili.modules.member.service.AccessTokenService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.member.serviceimpl.ExtensionServiceImpl;
import cn.lili.modules.member.token.AccessToken;
import cn.lili.modules.order.cart.entity.vo.TradeParams;
import cn.lili.modules.order.cart.service.CartService;
import cn.lili.modules.order.order.entity.dos.Trade;
import cn.lili.modules.permission.service.AdminUserService;
import cn.lili.modules.system.aspect.annotation.SystemLogPoint;
import cn.lili.modules.system.entity.dos.Region;
import cn.lili.modules.system.entity.dos.RegionDetail;
import cn.lili.modules.system.entity.vo.RegionDetailVO;
import cn.lili.modules.system.service.RegionDetailService;
import cn.lili.modules.system.service.RegionService;
import cn.lili.modules.transfer.entity.Transfer;
import cn.lili.modules.transfer.service.TransferService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.dos.Recharge;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.service.MemberWalletService;
import cn.lili.modules.wallet.service.RechargeService;
import cn.lili.modules.wechat.util.WechatMpCodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

import static cn.lili.common.enums.ResultCode.AUDIT_TYPE_ERROR;

/**
 * 管理端,会员接口
 *
 * @author Bulbasaur
 * @since 2020-02-25 14:10:16
 */
@RestController
@Api(tags = "管理端,会员接口")
@RequestMapping("/manager/member")
public class MemberManagerController {
	@Autowired
	private MemberService memberService;
	@Autowired
	private AdminUserService adminUserService;
	@Autowired
	private PartnerService partnerService;

	@Autowired
	private RegionService regionService;
	@Autowired
	private ExtensionServiceImpl extensionService;

	@Autowired
	private RechargeService rechargeService;

	@Autowired
	private CartService cartService;

	@Autowired
	private TransferService transferService;
	@Autowired
	private MemberWalletService memberWalletService;

	@Autowired
	private RegionDetailService regionDetailService;
	/**
	 * 缓存
	 */
	@Autowired
	private Cache cache;

	@Autowired
	public WechatMpCodeUtil wechatMpCodeUtil;

	@Autowired
	private AccessTokenService accessTokenService;

	@ApiOperation(value = "会员分页列表")
	@GetMapping
	public ResultMessage<IPage<MemberVO>> getByPage(MemberSearchVO memberSearchVO, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// if (null != adminUser) {
			// memberSearchVO.setExtension(adminUser.getPromotionCode());
			// }
			// 查询合伙人区域
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				memberSearchVO.setAdcode(partner.getRegionId());
			}
		}
		return ResultUtil.data(memberService.getMemberPage(memberSearchVO, page));
	}
	@ApiOperation(value = "会员列表不分页")
	@GetMapping("/getList")
	public ResultMessage<List<MemberVO>> getList(MemberSearchVO memberSearchVO) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// if (null != adminUser) {
			// memberSearchVO.setExtension(adminUser.getPromotionCode());
			// }
			// 查询合伙人区域
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				memberSearchVO.setAdcode(partner.getRegionId());
			}
		}
		return ResultUtil.data(memberService.getMemberList(memberSearchVO));
	}

	@RequestMapping("/mp/unlimited")
	@ApiOperation(value = "小程序太阳码生成：不限制数量，但是限制长度，只能存放32为长度")
	public ResultMessage<Map<String, Object>> unlimited(String page, String scene,String memberId) {
		Map<String, Object> map = new HashMap<>();
		Member member = memberService.getById(memberId);
		if (StringUtils.isEmpty(scene)) {
			scene = member.getPromotionCode();
		}
		String code = wechatMpCodeUtil.createCode(page, scene, ClientTypeEnum.WECHAT_MP);
		System.out.println(" ====================================================================== code：" + code);
		map.put("sunCode", code);
		return ResultUtil.data(map);
	}

	@ApiOperation(value = "无上级会员列表分页列表")
	@RequestMapping(value = "/noPartnerMemberList")
	public ResultMessage<IPage<MemberVO>> noPartnerMemberList(MemberSearchVO memberSearchVO, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (StringUtils.isNotEmpty(currentUser.getMemberId()))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// 通过用户名获取会员id
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				// memberSearchVO.setExtension(adminUser.getPromotionCode());
				// memberSearchVO.setRegion(partner.getRegion());
				memberSearchVO.setAdcode(partner.getRegionId());
			}
		}
		return ResultUtil.data(memberService.noPartnerMemberList(memberSearchVO, page));
	}

	@ApiOperation(value = "绑定无上级会员")
	@RequestMapping(value = "/bindingNoPartnerMemberList")
	@SystemLogPoint(description = "绑定会员", customerLog = "绑定会员请求", type = "2")
	public ResultMessage<Object> bindingNoPartnerMemberList(String id, String promotionCode,
			@RequestParam(value = "choseBindMemberIds") List<String> choseBindMemberIds) {
		if (StringUtils.isEmpty(promotionCode)) {
			return ResultUtil.success(ResultCode.USER_NOT_BINDING);
		}
		AuthUser currentUser = UserContext.getCurrentUser();
		int count = 0;
		for (String memberId : choseBindMemberIds) {
			Extension e = new Extension();
			e.setMemberId(memberId);
			e.setPartnerId(id);
			e.setExtension(promotionCode);
			e.setTempExtension(promotionCode);
			e.setCreateTime(new Date());
			e.setCreateBy(currentUser.getId());
			MemberVO memberVO = extensionService.findByMemberId(memberId);
			if (memberVO == null) {
				extensionService.addExtension(e);
				count++;
			}
		}
		if (count > 0) {
			return ResultUtil.success(ResultCode.SUCCESS);
		} else {
			return ResultUtil.success(ResultCode.USER_NOT_BINDING);
		}
	}

	@ApiOperation(value = "解绑会员")
	@RequestMapping(value = "/unBindingMemberList")
	public ResultMessage<Object> unBindingMemberList(
			@RequestParam(value = "choseBindMemberIds") List<String> choseBindMemberIds) {
		// 解绑会员
		Integer count = extensionService.updateBymemberId(choseBindMemberIds);
		if (count > 0) {
			return ResultUtil.success(ResultCode.SUCCESS);
		} else {
			return ResultUtil.success(ResultCode.USER_NOT_BINDING);
		}
	}

	@ApiOperation(value = "合伙人分页列表")
	@RequestMapping(value = "/partnerList")
	public ResultMessage<IPage<MemberVO>> getByPagePartner(MemberSearchVO memberSearchVO, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果手动传ID 用参数ID
		if (StringUtils.isNotEmpty(memberSearchVO.getMemberId())) {
			currentUser.setMemberId(memberSearchVO.getMemberId());
		}
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (StringUtils.isNotEmpty(currentUser.getMemberId()))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// 通过用户名获取会员id
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				// memberSearchVO.setExtension(adminUser.getPromotionCode());
				// memberSearchVO.setRegion(partner.getRegion());
				// memberSearchVO.setRegion(partner.getRegion());
				memberSearchVO.setAdcode(partner.getRegionId());
			}
		}
		// 没有禁用
		memberSearchVO.setDisabled("1");
		IPage<MemberVO> memberVOIPage = memberService.updatePartner(memberSearchVO, page);
		return ResultUtil.data(memberVOIPage);
	}

	@ApiOperation(value = "合伙人分页列表")
	@RequestMapping(value = "/getPartnerList")
	public ResultMessage<IPage<MemberVO>> getPartnerList(MemberSearchVO memberSearchVO, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (StringUtils.isNotEmpty(currentUser.getMemberId()))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// 通过用户名获取会员id
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				// memberSearchVO.setExtension(adminUser.getPromotionCode());
				// memberSearchVO.setRegion(partner.getRegion());
				memberSearchVO.setAdcode(partner.getRegionId());
			}
		}
		IPage<MemberVO> memberVOIPage = memberService.getPartnerList(memberSearchVO, page);

		return ResultUtil.data(memberVOIPage);
	}

	@ApiOperation(value = "合伙人分页列表 总合计数据")
	@RequestMapping(value = "/partnerListAll")
	public ResultMessage<MemberVO> getByPagePartnerAll(MemberSearchVO memberSearchVO) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果手动传ID 用参数ID
		if (StringUtils.isNotEmpty(memberSearchVO.getMemberId())) {
			currentUser.setMemberId(memberSearchVO.getMemberId());
		}
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (StringUtils.isNotEmpty(currentUser.getMemberId()))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// 通过用户名获取会员id
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				// memberSearchVO.setExtension(adminUser.getPromotionCode());
				// memberSearchVO.setRegion(partner.getRegion());
				// memberSearchVO.setRegion(partner.getRegion());
				memberSearchVO.setAdcode(partner.getRegionId());
			}
		}
		// 没有禁用
		memberSearchVO.setDisabled("1");
		MemberVO memberVO = memberService.countPartner(memberSearchVO);
		return ResultUtil.data(memberVO);
	}

	@ApiOperation(value = "异常合伙人分页列表合计")
	@RequestMapping(value = "/abnormalPartnerListAll")
	public ResultMessage<MemberVO> getByPageAbnormalPartnerListAll(MemberSearchVO memberSearchVO, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (StringUtils.isNotEmpty(currentUser.getMemberId()))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// 通过用户名获取会员id
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				// memberSearchVO.setExtension(adminUser.getPromotionCode());
				// memberSearchVO.setRegion(partner.getRegion());
				memberSearchVO.setAdcode(partner.getRegionId());
			}
		}
		// 禁用
		memberSearchVO.setDisabled("0");
		MemberVO memberVO = new MemberVO();
		memberVO.setRechargeMoney(0D);
		memberVO.setPromoteMoney(0D);
		memberVO.setPromoteHyMoney(0D);
		memberVO.setPromoteFwMoney(0D);
		memberVO.setSaleMoney(0D);
		memberVO.setAllMoney(0D);
		memberVO.setAllRechargeMoney(0D);
		memberVO.setAllYiBeiMoney(0D);
		page.setPageSize(999999999);
		IPage<MemberVO> memberVOIPage = memberService.updatePartner(memberSearchVO, page);
		if(memberVOIPage != null && CollectionUtils.isNotEmpty(memberVOIPage.getRecords())){
			for (MemberVO member:memberVOIPage.getRecords()) {
				memberVO.setRechargeMoney(CurrencyUtil.add(memberVO.getRechargeMoney(),member.getRechargeMoney() != null ? member.getRechargeMoney() : 0D));
				memberVO.setPromoteMoney(CurrencyUtil.add(memberVO.getPromoteMoney(),member.getPromoteMoney() != null ? member.getPromoteMoney() : 0D));
				memberVO.setPromoteHyMoney(CurrencyUtil.add(memberVO.getPromoteHyMoney(),member.getPromoteHyMoney() != null ? member.getPromoteHyMoney() : 0D));
				memberVO.setPromoteFwMoney(CurrencyUtil.add(memberVO.getPromoteFwMoney(),member.getPromoteFwMoney() != null ? member.getPromoteFwMoney() : 0D));
				memberVO.setSaleMoney(CurrencyUtil.add(memberVO.getSaleMoney(),member.getSaleMoney() != null ? member.getSaleMoney() : 0D));
				memberVO.setAllMoney(CurrencyUtil.add(memberVO.getAllMoney(),member.getAllMoney() != null ? member.getAllMoney() : 0D));
				memberVO.setAllRechargeMoney(CurrencyUtil.add(memberVO.getAllRechargeMoney(),member.getAllRechargeMoney() != null ? member.getAllRechargeMoney() : 0D));
				memberVO.setAllYiBeiMoney(CurrencyUtil.add(memberVO.getAllYiBeiMoney(),member.getAllYiBeiMoney() != null ? member.getAllYiBeiMoney() : 0D));
			}
		}
		return ResultUtil.data(memberVO);
	}

	@ApiOperation(value = "异常合伙人分页列表")
	@RequestMapping(value = "/abnormalPartnerList")
	public ResultMessage<IPage<MemberVO>> getByPageAbnormalPartnerList(MemberSearchVO memberSearchVO, PageVO page) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (StringUtils.isNotEmpty(currentUser.getMemberId()))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// 通过用户名获取会员id
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				// memberSearchVO.setExtension(adminUser.getPromotionCode());
				// memberSearchVO.setRegion(partner.getRegion());
				memberSearchVO.setAdcode(partner.getRegionId());
			}
		}
		// 禁用
		memberSearchVO.setDisabled("0");
		IPage<MemberVO> memberVOIPage = memberService.updatePartner(memberSearchVO, page);
		return ResultUtil.data(memberVOIPage);
	}

	@ApiOperation(value = "合伙人信息")
	@RequestMapping(value = "/partner/{id}")
	public ResultMessage<MemberVO> getByPagePartner(@PathVariable String id) {
		MemberSearchVO memberSearchVO = new MemberSearchVO();
		memberSearchVO.setId(id);
		IPage<MemberVO> memberVOIPage = memberService.updatePartner(memberSearchVO, new PageVO());
		return ResultUtil.data(memberVOIPage.getRecords() != null ? memberVOIPage.getRecords().get(0) : null);
	}

	@ApiOperation(value = "修改合伙人区域")
	@RequestMapping(value = "/updatePartner")
	public ResultMessage<Boolean> updatePartner(String id, String partnerRegion) {
		return ResultUtil.data(memberService.updatePartner(id, partnerRegion));
	}

	@ApiOperation(value = "修改区域列表")
	@RequestMapping(value = "/getRegionDetailList")
	public ResultMessage<IPage<RegionDetailVO>> getRegionDetailList(String id, PageVO page) {
		RegionDetailVO regionDetailVO = new RegionDetailVO();
		regionDetailVO.setMemberId(id);
		return ResultUtil.data(memberService.getRegionDetailList(regionDetailVO, page));
	}

	@ApiOperation(value = "修改用户区域")
	@RequestMapping(value = "/updateRegion")
	public ResultMessage<Boolean> updateRegion(String id, String region) {
		Member member = memberService.getById(id);
		String adCode = region;
		if (StringUtils.isNotEmpty(region)) {
			List<String> itemAdCod = regionService.getItemAdCod(region);
			if (itemAdCod != null && itemAdCod.get(0) != null)
				adCode = itemAdCod.get(0);
		}
		String location = "";
		Region itemAdCodAll = regionService.getItemAdCodAll(member.getLocation());
		if (itemAdCodAll != null) {
			String path = itemAdCodAll.getPath();
			if (StringUtils.isNotEmpty(path)) {
				String[] split1 = path.split(",");
				for (int a = 0; a < split1.length && a <= 3; a++) {
					Region byId = regionService.getById(split1[a]);
					if (byId != null)
						location += byId.getName();
				}
				location = location + itemAdCodAll.getName();
			}
		}
		String[] split2 = region.split(",");
		String adCodeName = "";
		for (int a = 0; a < split2.length && a <= 3; a++) {
			Region byId = regionService.getById(split2[a]);
			if (byId != null)
				adCodeName += byId.getName();
		}
		// 保留变更记录
		RegionDetail regionDetail = new RegionDetail();
		regionDetail.setMemberId(id);
		regionDetail.setBeforeAdCode(member.getLocation());
		regionDetail.setBeforeName(location);
		regionDetail.setAfterAdCode(adCode);
		regionDetail.setAfterName(adCodeName);
		// 修改区域
		member.setId(id);
		member.setLocation(adCode);
		QueryWrapper<Partner> wapper1 = new QueryWrapper<Partner>().eq("delete_flag", false).notIn("partner_type", 0, 3)
				.eq("member_id", id);
		List<Partner> list1 = partnerService.list(wapper1);
		if (list1.size() != 1) {
			regionDetailService.save(regionDetail);
			memberService.updateById(member);
			return ResultUtil.success();
		}
		// 是合伙人
		Partner partner = list1.get(0);
		if (4 == partner.getPartnerType()) {
			// 城市合伙人
			// 判断当前选中区域是否有城市合伙人
			QueryWrapper<Partner> wapper2 = new QueryWrapper<Partner>().eq("delete_flag", false).eq("partner_type", 4)
					.eq("audit_state", PartnerStatusEnum.PASS).eq("region_id", adCode);
			List<Partner> list2 = partnerService.list(wapper2);
			if (CollectionUtils.isNotEmpty(list2)) {
				return ResultUtil.error(ResultCode.PARTNER_LOCATION_ERROR);
			} else {
				regionDetailService.save(regionDetail);
				memberService.updateById(member);
				return ResultUtil.data(memberService.updatePartner(id, region));
			}
		} else {
			// 天使，事业合伙人
			regionDetailService.save(regionDetail);
			memberService.updateById(member);
			return ResultUtil.data(memberService.updatePartner(id, region));
		}
	}

	@ApiOperation(value = "合伙人审核")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "会员ID", required = true, dataType = "String", allowMultiple = true, paramType = "query"),
			@ApiImplicitParam(name = "auditState", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "auditRemark", value = "驳回理由", required = true, dataType = "String", paramType = "query")})
	@PutMapping("/auditPartner")
	@DemoSite
	@SystemLogPoint(description = "合伙人审核", customerLog = "合伙人审核请求", type = "2")
	public ResultMessage<Member> auditPartner(@Valid String id, String auditState, String auditRemark) {
		if (!"PASS".equals(auditState) && !"REFUSED".equals(auditState)) {
			return ResultUtil.error(AUDIT_TYPE_ERROR);
		}
		// 以转账的方式充值端口费
		TradeParams tradeParams = new TradeParams();
		QueryWrapper<Partner> queryWrapper = new QueryWrapper<Partner>().eq("delete_flag", false)
				.notIn("partner_type", 0, 3).in("audit_state", PartnerStatusEnum.REFUSED, PartnerStatusEnum.APPLYING)
				.eq("member_id", id).last("limit 1");
		Partner partner = partnerService.getOne(queryWrapper);
		if (StringUtils.isNotEmpty(partner.getSn())) {
			Recharge recharge = rechargeService.getRecharge(partner.getSn());
			Member payee = memberService.getById(partner.getMemberId()); // 收款人
			tradeParams.setWay("PORT_FEE");
			tradeParams.setClient("WECHAT_MP");
			tradeParams.setCommission(recharge.getRechargeMoney());
			tradeParams.setOwner("RECHARGE");
			tradeParams.setPrice(recharge.getRechargeMoney());
			tradeParams.setPayeePhone(payee.getMobile());
			Trade trade = this.cartService.crateTransferTrade(tradeParams);
			MemberWallet from = memberWalletService.getMemberWalletInfo("admin", WalletOwnerEnum.PROMOTE_FW.name(),
					"平台");// 付款人
			MemberWallet to = memberWalletService.getMemberWalletInfo(payee.getId(), WalletOwnerEnum.RECHARGE.name());
			// 通过交易表的sn查询转账表的sn
			Transfer transferBySn = transferService.getTransferByTradeSn(trade.getSn());
			boolean flag = memberWalletService.transferPay(transferBySn.getSn(), from, to, recharge.getRechargeMoney(),
					0.0, tradeParams.getWay());
		}

		memberService.auditPartner(id, auditState, auditRemark);
		return ResultUtil.success();
	}

	@ApiOperation(value = "添加会员")
	@PostMapping
	public ResultMessage<Member> save(@Valid MemberAddDTO member) {

		return ResultUtil.data(memberService.addMember(member));
	}

	@ApiOperation(value = "修改会员基本信息")
	@PutMapping
	@DemoSite
	public ResultMessage<Member> update(@Valid ManagerMemberEditDTO managerMemberEditDTO) {
		return ResultUtil.data(memberService.updateMember(managerMemberEditDTO));
	}

	@ApiOperation(value = "启用/禁用合伙人状态")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "会员ID", required = true, dataType = "String", allowMultiple = true, paramType = "query"),
			@ApiImplicitParam(name = "partnerState", required = true, dataType = "Integer", paramType = "query")})
	@PutMapping("/updatePartner")
	@DemoSite
	public ResultMessage<Member> updatePartner(@RequestParam List<String> id, Integer partnerState) {
		boolean b = partnerState == 0 ? true : false;
		memberService.updateMemberStatus(id, b);
		return ResultUtil.success();
	}

	@ApiOperation(value = "修改会员状态,开启关闭会员")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "memberIds", value = "会员ID", required = true, dataType = "String", allowMultiple = true, paramType = "query"),
			@ApiImplicitParam(name = "disabled", required = true, dataType = "boolean", paramType = "query")})
	@PutMapping("/updateMemberStatus")
	@DemoSite
	@SystemLogPoint(description = "启用、关闭异常会员", customerLog = "'启用、关闭异常会员请求", type = "2")
	public ResultMessage<Object> updateMemberStatus(@RequestParam List<String> memberIds,
			@RequestParam Boolean disabled) {
		memberService.updateMemberStatus(memberIds, disabled);
		// 清除登录状态
		for (String memberId : memberIds) {
			AccessToken accessToken = accessTokenService.getById(memberId);
			if (accessToken != null) {
				// String accessToken =
				// "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyQ29udGV4dCI6IntcInVzZXJuYW1lXCI6XCJtMTU2NTcxMjU2MjdcIixcIm5pY2tOYW1lXCI6XCLliKvor7Tor53jgIJcIixcImZhY2VcIjpcImh0dHBzOi8vdGhpcmR3eC5xbG9nby5jbi9tbW9wZW4vdmlfMzIvVU1qRVBseU5GTlRXcTJCSkJWM1VxV0VMUjhjUzBpY1VWRG1QdEVGb2FUZW9reXFwY0VxTmdJbTNKaWFuS1ZsbnpGWkp2V0VycTdpY1hJRUtQeVp1Z1ZJbkEvMTMyXCIsXCJpZFwiOlwiMTU3MzExOTkzMzgxNDQ3MjcwNVwiLFwibG9uZ1Rlcm1cIjp0cnVlLFwicm9sZVwiOlwiTUVNQkVSXCIsXCJpc1N1cGVyXCI6ZmFsc2UsXCJwdXJlUGhvbmVOdW1iZXJcIjpcIjE1NjU3MTI1NjI3XCIsXCJtZW1iZXJJZFwiOlwiMTU3MzExOTkzMzgxNDQ3MjcwNVwifSIsInN1YiI6Im0xNTY1NzEyNTYyNyIsImV4cCI6MTY2MzkxNzQ3Mn0.GzpePskHp_JP5MmS5EsLBFBQjBJZnc3abdPPjyyD7Cc";
				if (CharSequenceUtil.isNotEmpty(accessToken.getAccessToken())) {
					cache.remove(CachePrefix.ACCESS_TOKEN.getPrefix(UserEnums.MEMBER) + accessToken.getAccessToken());
					accessTokenService.removeByAccessToken(accessToken.getAccessToken());
				}
			}
		}
		return ResultUtil.success();
	}

	@ApiOperation(value = "根据条件查询会员总数")
	@RequestMapping("/num")
	public ResultMessage<Long> getByPage(MemberSearchVO memberSearchVO) {
		return ResultUtil.data(memberService.getMemberNum(memberSearchVO));
	}

	@ApiOperation(value = "清空回收站")
	@RequestMapping("/clean")
	public ResultMessage<Object> clean() {
		memberService.cleanMember();
		return ResultUtil.success();
	}

	@ApiOperation(value = "商家会员列表")
	@RequestMapping("/getmemSto")
	public ResultMessage<IPage<MemberStoreVO>> getmemSto(MemberStoreVO mmberStoreVO, PageVO page) {
		return ResultUtil.data(memberService.getmemSto(mmberStoreVO, page));
	}

	@ApiOperation(value = "通过ID获取会员信息")
	@ApiImplicitParam(name = "id", value = "会员ID", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/getAllMember")
	public ResultMessage<MemberDetailsVo> get(MemberDetailsVo memberDetailsVo) {

		return ResultUtil.data(memberService.getMemberDetails(memberDetailsVo));
	}

	@ApiOperation(value = "充值收入列表")
	@RequestMapping("/getIncome")
	public ResultMessage<IPage<MemberIncomeVo>> getIncomeByPage(MemberIncomeVo memberIncomeVo, PageVO page) {
		return ResultUtil.data(memberService.getIncomeByPage(memberIncomeVo, page));
	}

	@ApiOperation(value = "充值收入列表求和")
	@RequestMapping("/getIncomeByPageCount")
	public ResultMessage<Map<String, Object>> getIncomeByPageCount(MemberIncomeVo memberIncomeVo) {
		return ResultUtil.data(memberService.getIncomeByPageCount(memberIncomeVo));
	}

	@ApiOperation(value = "充值支出列表")
	@RequestMapping("/getBranch")
	public ResultMessage<IPage<MemberExpenditureVo>> getBranchByPage(MemberExpenditureVo memberIncomeVo, PageVO page) {
		return ResultUtil.data(memberService.getBranchByPage(memberIncomeVo, page));
	}

	@ApiOperation(value = "充值支出列表求和")
	@RequestMapping("/getBranchByPageCount")
	public ResultMessage<Map<String, Object>> getBranchByPageCount(MemberExpenditureVo memberIncomeVo) {
		return ResultUtil.data(memberService.getBranchByPageCount(memberIncomeVo));
	}

	@ApiOperation(value = "销售收入列表")
	@RequestMapping("/getIncomeSale")
	public ResultMessage<IPage<MemberIncomeVo>> getIncomeSaleByPage(MemberIncomeVo memberIncomeVo, PageVO page) {
		return ResultUtil.data(memberService.getIncomeSaleByPage(memberIncomeVo, page));
	}

	@ApiOperation(value = "销售收入列表求和")
	@RequestMapping("/getIncomeSaleByPageCount")
	public ResultMessage<Map<String, Object>> getIncomeSaleByPageCount(MemberIncomeVo memberIncomeVo) {
		return ResultUtil.data(memberService.getIncomeSaleByPageCount(memberIncomeVo));
	}

	@ApiOperation(value = "销售支出列表")
	@RequestMapping("/getBranchSale")
	public ResultMessage<IPage<MemberExpenditureVo>> getBranchSaleByPage(MemberExpenditureVo memberIncomeVo,
			PageVO page) {
		return ResultUtil.data(memberService.getBranchSaleByPage(memberIncomeVo, page));
	}

	@ApiOperation(value = "支出列表求和")
	@RequestMapping("/getBranchSaleByPageCount")
	public ResultMessage<Map<String, Object>> getBranchSaleByPageCount(MemberExpenditureVo memberIncomeVo) {
		return ResultUtil.data(memberService.getBranchSaleByPageCount(memberIncomeVo));
	}

	@ApiOperation(value = "推广收入列表")
	@RequestMapping("/getIncomePromote")
	public ResultMessage<IPage<MemberIncomeVo>> getIncomePromoteByPage(MemberIncomeVo memberIncomeVo, PageVO page) {
		return ResultUtil.data(memberService.getIncomePromoteByPage(memberIncomeVo, page));
	}

	@ApiOperation(value = "推广收入列表求和")
	@RequestMapping("/getIncomePromoteByPageCount")
	public ResultMessage<Map<String, Object>> getIncomePromoteByPageCount(MemberIncomeVo memberIncomeVo) {
		return ResultUtil.data(memberService.getIncomePromoteByPageCount(memberIncomeVo));
	}

	@ApiOperation(value = "推广支出列表")
	@RequestMapping("/getBranchPromote")
	public ResultMessage<IPage<MemberExpenditureVo>> getBranchPromoteByPage(MemberExpenditureVo memberIncomeVo,
			PageVO page) {
		return ResultUtil.data(memberService.getBranchPromoteByPage(memberIncomeVo, page));
	}

	@ApiOperation(value = "推广支出列表求和")
	@RequestMapping("/getBranchPromoteByPageCount")
	public ResultMessage<Map<String, Object>> getBranchPromoteByPageCount(MemberExpenditureVo memberIncomeVo) {
		return ResultUtil.data(memberService.getBranchPromoteByPageCount(memberIncomeVo));
	}

	@ApiOperation(value = "异常会员分页列表")
	@RequestMapping("/getDisableMemberPage")
	public ResultMessage<IPage<MemberAbnormalVo>> getDisableMemberPage(MemberAbnormalVo memberAbnormalVo, PageVO page) {
		return ResultUtil.data(memberService.getDisableMemberPage(memberAbnormalVo, page));
	}

	@ApiOperation(value = "获取下级会员列表(天使/事业/焕商天使)")
	@RequestMapping("/getDisableMemberPageAll")
	public ResultMessage<IPage<MemberVO>> getDisableMemberPageAll(MemberSearchVO memberSearchVO, PageVO page) {
		IPage<MemberVO> p = memberService.getDisableMemberPageAll(memberSearchVO, page);
		if (p != null) {
			return ResultUtil.data(p);
		} else {
			return ResultUtil.data(new Page<>());
		}
	}

	@ApiOperation(value = "获取下级会员列表(城市合伙人)")
	@RequestMapping("/getDisableMemberPageAll2")
	public ResultMessage<IPage<MemberVO>> getDisableMemberPageAll2(MemberSearchVO memberSearchVO, PageVO page) {
		IPage<MemberVO> p = memberService.getDisableMemberPageAll2(memberSearchVO, page);
		if (p != null) {
			return ResultUtil.data(p);
		} else {
			return ResultUtil.data(new Page<>());
		}
	}

	@ApiOperation(value = "C端会员分页列表")
	@RequestMapping(value = "/getCMemberList")
	public ResultMessage<IPage<MemberVO>> getMemberByPage(MemberSearchVO memberSearchVO, PageVO page) {
		return ResultUtil.data(memberService.getMemberListPage(memberSearchVO, page));
	}
	@ApiOperation(value = "C端会员分页合计")
	@RequestMapping(value = "/getCMemberListAll")
	public ResultMessage<Map<String, Object>> getMemberList(MemberSearchVO memberSearchVO, PageVO page) {
		Map<String ,Object> map = new HashMap<>();
		Double rechargeMoney = 0D;
		page.setPageSize(999999999);
		IPage<MemberVO> memberListPage = memberService.getMemberListPage(memberSearchVO, page);
		if(memberListPage != null ){
			for (MemberVO member:memberListPage.getRecords()) {
				rechargeMoney = CurrencyUtil.add(rechargeMoney,member.getRechargeMoney() != null ? member.getRechargeMoney() : 0D);
			}
		}
		map.put("rechargeMoney",rechargeMoney);
		return ResultUtil.data(map);
	}
}
